package com.mrx.compose.demo.api

import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.TypeReference
import com.mrx.compose.demo.model.request.UserModel
import com.mrx.compose.demo.model.response.BaseResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.slf4j.LoggerFactory

/**
 * @author Mr.X
 * @since 2024-05-29 10:03
 **/
object LoginApi {

    private const val BASE_URL = "http://localhost:8080"

    private const val LOGIN_PATH = "/user/login"

    private val client = OkHttpClient.Builder()
        .addInterceptor(this::intercept)
        .build()

    private val logger = LoggerFactory.getLogger(this::class.java)

    suspend fun login(userModel: UserModel) = withContext(Dispatchers.IO) {
        runCatching {
            logger.info("Login: $userModel")
            val request = Request.Builder()
                .url(BASE_URL + LOGIN_PATH)
                .post(userModel.toRequestBody())
                .build()
            val responseBody = client.newCall(request).execute().body!!.string()
            return@runCatching JSON.parseObject(responseBody, object : TypeReference<BaseResponse<String>>() {})
        }.onFailure {
            logger.error("出现异常: $it")
        }
    }

    private fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        logger.info("${request.method} -> ${request.url}")
        return chain.proceed(request)
    }

}